package com.algorithm.labuladong.binarytree;

import lombok.Data;

/**
 * @author: tzj
 * @create: 2021-08-11
 **/
@Data
class BinaryTree {
    public Node node;

    public BinaryTree() {
    }

    public BinaryTree(Node node) {
        this.node.leftChild = node.leftChild;
        this.node.rightChild = node.rightChild;
    }

    /**
     * 左插入节点
     *
     * @param curr_node
     * @param element
     * @return
     */
    public Node insertLeftChild(Node curr_node, Object element) {
        if (curr_node == null) {
            return null;
        }
        // 初始化新节点
        Node newNode = new Node();
        newNode.data = element;
        // 插入新节点左子树为原子树node的左子树（---> null）
        newNode.leftChild = curr_node.leftChild;
        newNode.rightChild = null;

        // 转换curr_node节点为当前插入后的左子树
        curr_node.leftChild = newNode;
        return curr_node.leftChild;
    }

    /**
     * 右插入节点
     *
     * @param curr_node
     * @param element
     * @return
     */
    public Node insertRightChild(Node curr_node, Object element) {
        if (curr_node == null) {
            return null;
        }

        Node newNode = new Node();
        newNode.data = element;
        newNode.rightChild = newNode;
        newNode.rightChild = null;

        curr_node.rightChild = newNode;
        return curr_node.rightChild;
    }

    /**
     * 打印二叉树
     *
     * @param root
     * @param n
     */
    public void printf(Node root, int n) {
        // 为空判断
        if (root == null) {
            return;
        }

        // 遍历打印右子树
        printf(root.rightChild, n + 1);

        for (int i = 0; i < n - 1; i++) {
            System.out.print("\t");
        }

        if (n > 0) {
            System.out.println("----" + root.data);
        }
        printf(root.leftChild, n + 1);
    }

    /**
     * 前序遍历
     *
     * @param root
     */
    public void preOrder(Node root) {
        if (root != null) {
            if (root.data != null) {
                System.out.print(root.data + " ");
            }
            preOrder(root.leftChild);
            preOrder(root.rightChild);
        }
    }

    /**
     * 中序遍历
     *
     * @param root
     */
    public void inOrder(Node root) {
        if (root != null) {
            inOrder(root.leftChild);
            if (root.data != null) {
                System.out.print(root.data + " ");
            }
            inOrder(root.rightChild);
        }
    }

    /**
     * 后序遍历
     *
     * @param root
     */
    public void postOrder(Node root) {
        if (root != null) {
            postOrder(root.leftChild);
            postOrder(root.rightChild);
            if (root.data != null) {
                System.out.print(root.data + " ");
            }
        }
    }

    static class Node {
        public Object data;
        // 左节点
        public Node leftChild;
        // 右节点
        public Node rightChild;

        public Node() {
        }
    }
}
